#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <usiTwiSlave.h> 

# define LED PB1 // Define ext led pin on PB0 *2
# define ADC2_PB4 0b00000010;

float spannung;

// attiny code
int main(void)
{
  // set LED to on for +5V 
  DDRB |= (1 << LED); // Set output direction on LED
  PORTB |= (1 << LED);

  ADCSRA = (1<<ADEN) | (1<<ADPS1) | (1<<ADPS0);     // Prescaler und Enable
  ADMUX = ADC2_PB4;                                // select channel

  // einma warm werden lassen ...
  ADCSRA |= (1<<ADSC);               // single converson
  while ( ADCSRA & (1<<ADSC) );      // warten bis fertig
  spannung = ADCW;                    // spannung auslesen
  spannung = 0;                        // wegschmeissen  

  // initialize as slave with id 1
  usiTwiSlaveInit(25);
  
  // enable interrupts (must be there, i2c needs them!)
  sei();

  // handle commands
  while (1)
  {
    ADMUX = ADC2_PB4;
    spannung = 0;
    ADCSRA |= (1<<ADSC);                // single conversion
    while ( ADCSRA & (1<<ADSC) );      // warten bis fertig
    spannung += ADCW;                    // spannung auslesen
    uint8_t ana_wert = spannung * 100 / 1024;    // Spanungswert errechnen

    // check if data is in the i2c receive buffer
    if(usiTwiDataInReceiveBuffer())
    {
      // get it
      uint8_t b = usiTwiReceiveByte();
      // echo it back
      usiTwiTransmitByte(ana_wert);
    }
    // Do something else while waiting for the TWI transceiver to complete.

    asm volatile ("NOP" ::);
  }
  return 0;
}
